<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form :model="formModel"
               label-position="right"
               ref="formModelRef"
               label-width="150px"
               :rules='formModelRules'>
        <el-form-item label="活动名称："
                      prop="name">
          <el-input v-model="formModel.name"
                    class="w-200"
                    placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="参与公司：">
          <el-select v-model="selectIds"
                     ref="selectDom"
                     placeholder="请选择参与公司"
                     multiple
                     filterable
                     remote
                     reserve-keyword
                     :remote-method="(query) => {remoteMethod(query, 'company')}"
                     :loading="loading1"
                     class="w-200"
                     @change="val=>handleSelect(val, 'company')">
            <el-option v-for="item in optionsFilter"
                       :key="item.companyId"
                       :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
          <el-button type="primary"
                     @click="handleAdd(selectIds)">增 加
          </el-button>
        </el-form-item>
        <el-form-item label="已选择：">
          <el-table :data="formModel.activityBeforeAppointmentCompanyDtos"
                    style="width: 50%"
                    border>
            <el-table-column prop="companyName"
                             label="机构名称">
            </el-table-column>
            <!-- <el-table-column prop="address"
                             label="机构地址">
            </el-table-column> -->
            <el-table-column prop="op"
                             label="操作"
                             width="120">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delRow(formModel.activityBeforeAppointmentCompanyDtos, scope.$index)">移 除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="预约截止日期："
                      prop="expirationDate">
          <el-date-picker v-model="formModel.expirationDate"
                          type="date"
                          value-format="timestamp"
                          clearable
                          placeholder="选择预约截止日期"
                          :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约奖励："
                      prop="appointmentAward">
          <el-input-number v-model="formModel.appointmentAward"
                           placeholder="请输入预约奖励"
                           :min="0"
                           :controls="false"
                           class="w-200"></el-input-number>
        </el-form-item>
        <el-form-item label="预约活动激励名额："
                      prop="limitNum">
          <el-input-number v-model="formModel.limitNum"
                           placeholder="请输入预约活动激励名额"
                           :min="0"
                           :controls="false"
                           class="w-200"></el-input-number>
        </el-form-item>
        <el-form-item label="活动介绍："
                      prop="introduceUrl">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     :on-success="handlePictureCardPreview"
                     :before-upload="beforeAvatarUpload">
            <img v-if="formModel.introduceUrl"
                 :src="formModel.introduceUrl"
                 style="width:100px;height:100px;"/>
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="关联病种：" class="is-required">
          <el-select v-model="formModel.healthMapDiseaseDtos"
                     placeholder="请选关联病种"
                     filterable
                     multiple
                     remote
                     value-key="id"
                     :remote-method="(query) => {remoteMethod(query, 'diseases')}"
                     :loading="loading1"
                     class="w-200"
                     clearable
                     @change="val=>handleSelect(val, 'diseases')">
            <el-option v-for="item in diseasesFilterList"
                       :key="item.id"
                       :label="item.name"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button @click="modalClose"
                   type="info">取 消
        </el-button>
        <el-button type="primary"
                   @click="submitForm">保 存
        </el-button>
      </p>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'reserveDialog', // 活动预约弹窗
  props: {
    dataObj: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      title: '新 增',
      loading: false,
      loading1: false,
      loading2: false,
      imageUploadUrl: this.api.appUpgradeUpload.url,
      formModel: {
        name: '',
        expirationDate: '', // 预约截止日期
        appointmentAward: 0, // 预约奖励
        limitNum: 0, // 预约活动激励名额
        introduce: '', // 活动介绍
        activityBeforeAppointmentCompanyDtos: [],
        healthMapDiseaseDtos: [],
        healthMapDiseaseId: ''
      },
      selectIds: [],
      formModelRules: {
        name: [{required: true, message: '请输入活动名称', trigger: 'blur'}],
        expirationDate: [{type: 'date', required: true, message: '选择预约截止日期', trigger: ['blur', 'chagne']}],
        appointmentAward: [{required: true, message: '请输入预约奖励', trigger: 'blur'}],
        limitNum: [{required: true, message: '请输入预约活动激励名额', trigger: 'blur'}],
        introduceUrl: [{required: true, message: '请上传活动介绍图片', trigger: ['blur', 'chagne']}],

      },
      options: [],
      optionsFilter: [],
      pickerOptions: { // 禁用当前日期之前的日期
        disabledDate(time) {
          // Date.now()是javascript中的内置函数，它返回自1970年1月1日00:00:00 UTC以来经过的毫秒数。
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      pageIndex: 1,
      pageSize: 200,
      diseasesList: [],
      diseasesFilterList: [],
    }
  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    // 保存
    submitForm() {

      const cloneData = JSON.parse(JSON.stringify(this.formModel));
      // cloneData.healthMapDiseaseDtos = arr;
      // cloneData.healthMapDiseaseId = JSON.stringify(cloneData.healthMapDiseaseId);
      this.$refs.formModelRef.validate(async (valid) => {
        if (valid) {
          if (this.formModel.activityBeforeAppointmentCompanyDtos.length === 0) {
            this.$message.error('请选择参与公司!');
            return
          } else if (this.formModel.healthMapDiseaseDtos.length === 0) {
            this.$message.error('请选择关联病种!');
            return
          }
          // 新增、编辑保存
          const {data: res} = await this.post(this.api.promote.updateAppointment, cloneData);
          if (res.code === '200') {
            this.$message.success('保存成功!');
            this.$parent.getList(); // 调用父件组方法
            this.modalClose();
          }
        }
      })
    },

    // 远程搜索参与公司
    remoteMethod(query, type) {
      // if (query !== '') {
      let _this = this;
      // if (query) {
      if (type === 'company') {
        _this.loading1 = true;
        this.post(this.api.company.companyList, {
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
          name: query,
          hospitalType: '',
          status: 1
        }).then(res => {
          if (res.data.code === '200') {
            _this.loading1 = false;
            _this.options = res.data.object.map(({
                                                   id,
                                                   name,
                                                   address
                                                 }) => ({
              companyId: id,
              companyName: name,
              address
            }));
          }
        })
        setTimeout(() => {
          _this.loading1 = false;
          _this.optionsFilter = _this.options.filter(item => item.companyName.indexOf(query) > -1);
        }, 200)
      }
      if (type === 'diseases') {
        _this.loading2 = true;
        // let query = query ? query.trim() : '';
        this.post(this.api.healthMap.getHealthMapDiseaseList, {
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
          name: query
        }).then(res => {
          if (res.data.code === '200') {
            _this.loading2 = false;
            _this.diseasesList = res.data.object;
          }
        })
        setTimeout(() => {
          _this.loading2 = false;
          _this.diseasesFilterList = _this.diseasesList.filter(item => item.name.indexOf(query) > -1);
        }, 200)
      }
      // }


      /*  } else {
         if (type === 'company') {
           this.optionsFilter = [];
         }
         if (type === 'diseases') {
           this.diseasesFilterList = [];
         }
       } */
    },

    handleSelect(item, option) {

      if (option === 'company') {
        this.selectIds = item.map(x => x.id);
      }
    },
    focusVal() {
      this.remoteMethod('', 'diseases');
    },
    // 增加机构
    handleAdd(ids) {
      if (ids.length === 0) {
        this.$message.warning('请选择参与公司!');
        return
      }
      if (this.formModel.activityBeforeAppointmentCompanyDtos.some(item => ids.includes(item.companyId))) {
        this.$message.warning('不能重复添加参与公司!');
        this.selectIds = [];
        return
      }
      let temp = this.optionsFilter.filter(item => ids.some(ele => ele === item.companyId));
      this.formModel.activityBeforeAppointmentCompanyDtos = [...this.formModel.activityBeforeAppointmentCompanyDtos, ...temp];
      this.selectIds = [];
    },

    // 删除已选机构
    delRow(table, index) {
      table.splice(index, 1);
    },
    // 上传前的方法
    beforeAvatarUpload(file) {
      let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp']
      const isType = types.includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isType) {
        this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!');
        return isType;
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return isLt10M;
      }
    },
    // 上传单张图片
    handlePictureCardPreview(response, file, fileList) {
      if (response.code === '200') {
        // 状态码为200时则上传成功
        this.$set(this.formModel, 'introduceUrl', file.response.object[0]);
        this.$message.success('上传成功');
      } else {
        // 状态码不是200时上传失败 从列表中删除
        fileList.splice(fileList.indexOf(file), 1);
        this.$message.error(response.message);
      }
    },
  },
  created() {
    if (this.dataObj) {
      this.title = '编 辑';
      this.formModel = this.dataObj;
      this.diseasesFilterList = this.dataObj.healthMapDiseaseDtos;
      this.formModel.healthMapDiseaseId = ''
      // this.formModel.healthMapDiseaseId = this.dataObj.healthMapDiseaseDtos.map(item => item.id);
    }
  },
}
</script>
<style scoped lang="scss">
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;

}
</style>
